﻿using Common.Helper;
using IRepository;
using IService.Blog;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Blog
{
    public class ArticleService: IArticleService
    {
        readonly ILogger<ArticleService> logger;
        readonly IBaseRepository baseRepository;
        public ArticleService(ILogger<ArticleService> _logger, IBaseRepository _baseRepository)
        {
            logger = _logger;
            baseRepository = _baseRepository;
        }

        #region Get

        /// <summary>
        /// 查询所有博文（分页）
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllToPage(int offset,int limit)
        {
            try
            {
                PageInfoModel<BArticle> pageList = await baseRepository.QueryPage<BArticle>(offset, limit, "ID");
                //List<BArticle> parameters = await baseRepository.Query<BArticle>();

                PageInfoModel<object> list = new PageInfoModel<object>();
                list.DataCount = pageList.DataCount;
                list.PageSize = pageList.PageSize;
                list.PageCount = pageList.PageCount;
                list.Page = pageList.Page;
                list.Data = new List<object>();
                foreach (var item in pageList.Data)
                {
                    BSort sort = baseRepository.Query<BSort>(n => n.ID == item.SortID).Result.FirstOrDefault();
                    list.Data.Add(new {
                        id=item.Id,
                        articleTitle = item.ArticleTitle,
                        articleContent = item.ArticleContent,
                        sortName = sort.SortName,
                        sortID = sort.ID,
                        isHot = item.IsHot,
                        isRecommend=item.IsRecommend,
                        viewsCount = item.ViewsCount,
                        articleCover=item.ArticleCover,
                        commentsCount = item.CommentsCount,
                        isTop = item.IsTop,
                        isPublish = item.IsPublish,
                        createdAt = item.CreatedAt,
                        updatedAt = item.UpdatedAt,
                        tagID = item.TagID,
                        articleSummary=item.ArticleSummary
                    });
                };

                string result = JsonConvert.SerializeObject(list);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询所有博文（分页--前端查询）
        /// </summary>
        /// <param name="paging"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllToMoer(Paging paging)
        {
            try
            {
                PageInfoModel<BArticle> pageList = await baseRepository.QueryPage<BArticle>(paging.offset, paging.limit, paging.sortName);
                if (paging.isRecommend)
                {
                    pageList.Data = pageList.Data.OrderByDescending(n => n.IsTop).ThenByDescending(n => n.IsRecommend).ThenByDescending(n=>n.UpdatedAt).ToList();
                }

                PageInfoModel<object> list = new PageInfoModel<object>();
                list.DataCount = pageList.DataCount;
                list.PageSize = pageList.PageSize;
                list.PageCount = pageList.PageCount;
                list.Page = pageList.Page;
                list.Data = new List<object>();
                foreach (var item in pageList.Data)
                {
                    BSort sort = baseRepository.Query<BSort>(n => n.ID == item.SortID).Result.FirstOrDefault();
                    list.Data.Add(new
                    {
                        id = item.Id,
                        articleTitle = item.ArticleTitle,
                        articleContent = item.ArticleContent,
                        sortName = sort.SortName,
                        sortID = sort.ID,
                        isHot = item.IsHot,
                        isRecommend = item.IsRecommend,
                        viewsCount = item.ViewsCount,
                        articleCover = item.ArticleCover,
                        commentsCount = item.CommentsCount,
                        isTop = item.IsTop,
                        isPublish = item.IsPublish,
                        createdAt = item.CreatedAt,
                        updatedAt = item.UpdatedAt,
                        tagID = item.TagID,
                        articleSummary=item.ArticleSummary
                    });
                };

                string result = JsonConvert.SerializeObject(list);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="blurCon">模糊条件</param>
        /// <returns></returns>
        public async Task<MessageModel<List<BArticle>>> GetFuzzyQuery(string blurCon)
        {
            try
            {
                List<BArticle> result = new List<BArticle>();
                if (!string.IsNullOrEmpty(blurCon))
                {
                    result = await baseRepository.Query<BArticle>();
                    result = result.Where(n => n.ArticleTitle.Contains(blurCon) || n.ArticleContent.Contains(blurCon)).ToList();
                    return new MessageModel<List<BArticle>>()
                    {
                        Code = 20000,
                        Data = result,
                        Message = "查询成功",
                        Success = true
                    };
                }
                return new MessageModel<List<BArticle>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BArticle>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询所有博文
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BArticle>>> GetAll()
        {
            try
            {
                List<BArticle> result = await baseRepository.Query<BArticle>();
                return new MessageModel<List<BArticle>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BArticle>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 根据条件表达式查询数据列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>数据列表</returns>
        public async Task<MessageModel<List<BArticle>>> GetByExpression<BArticle>(Expression<Func<BArticle, bool>> whereExpression)
        {
            try
            {
                List<BArticle> result = await baseRepository.Query(whereExpression);
                //LogLock.OutLogFile("GetByExpression", JsonConvert.SerializeObject(whereExpression), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BArticle>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BArticle>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 查询博文按ID--前端
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetByIdToPage(int id)
        {
            try
            {
                BArticle article = await baseRepository.Query<BArticle>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                BSort sort= await baseRepository.Query<BSort>(article.SortID);
                var arr=article.TagID.Split(',');
                List<string> list = new List<string>();

                foreach (var item in arr)
                {
                    BTag tag= await baseRepository.Query<BTag>(Convert.ToInt32(item));
                    list.Add(tag.TagName);
                }
                object obj = new {
                    id = article.Id,
                    articleTitle = article.ArticleTitle,
                    articleContent = article.ArticleContent,
                    sortName = sort.SortName,
                    sortID = sort.ID,
                    isHot = article.IsHot,
                    isRecommend = article.IsRecommend,
                    viewsCount = article.ViewsCount,
                    articleCover = article.ArticleCover,
                    commentsCount = article.CommentsCount,
                    isTop = article.IsTop,
                    isPublish = article.IsPublish,
                    createdAt = article.CreatedAt,
                    updatedAt = article.UpdatedAt,
                    tagID = article.TagID,
                    articleSummary = article.ArticleSummary,
                    tagNames=list
                };
                string result = JsonConvert.SerializeObject(obj);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 按类别ID查询博文
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MessageModel<BArticle>> GetById(int id)
        {
            try
            {
                BArticle result = await baseRepository.Query<BArticle>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<BArticle>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BArticle>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 按类别ID查询博文
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BArticle>>> GetBySortId(int id)
        {
            try
            {
                List<BArticle> result = await baseRepository.Query<BArticle>(n=>n.SortID==id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BArticle>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BArticle>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Post
        /// <summary>
        /// 添加博文
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Post(BArticle parameter)
        {
            try
            {
                parameter.CreatedAt = DateTime.Now;
                parameter.Id = await baseRepository.Add(parameter);
                return new MessageModel<string>()
                {
                    Code = 200,
                    Data = parameter.Id.ObjToString(),
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Put
        /// <summary>
        /// 修改博文
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Put(BArticle parameter)
        {
            try
            {
                parameter.UpdatedAt = DateTime.Now;
                bool flag = await baseRepository.Update(parameter);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = parameter.Id.ObjToString(),
                        Message = "修改成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "修改失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除博文
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DelById(int id)
        {
            try
            {
                bool flag = await baseRepository.DeleteById<BArticle>(id);
                //LogLock.OutLogFile("DelById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(flag), true);//存入日志
                return new MessageModel<bool>()
                {
                    Code = 200,
                    Data = flag,
                    Message = "删除成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

    }
}
